import { MES_LXK_ApiHost } from '@/utils/Interceptors'

// 产品信息接口
export interface Product {
  id: number
  productId: number
  productName: string
  productNumber: string
  productSpecification: string
  inventoryUnit: string
  productAttribute?: string
  processRoute?: string
  maxInventory: number
  minInventory: number
  safetyInventory: number
  num: number
  current: number
  createdTime: string
  createdBy: string
  modifiedBy: string | null
  modifiedTime: string | null
  isDelete: boolean
}

// 入库单明细接口
export interface InboundOrderDetail {
  id?: number
  productId: number
  productName: string
  productCode: string
  productSpecification: string
  unit: string
  productAttribute?: string
  processRoute?: string
  maxInventory: number
  minInventory: number
  safetyStock: number
  currentInventory: number
  num: number
  createdBy?: string
  createdTime?: string
}

// 入库单数据接口
export interface InboundOrder {
  storageId: number
  entryOrderNumber: string
  entryType: string
  entryTime: string
  remarks: string
  createdTime: string
  createdBy: string
  modifiedBy: string
  modifiedTime: string
  isDelete: boolean
  details?: InboundOrderDetail[]
}

// API响应接口
export interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

// 搜索参数接口
export interface SearchParams {
  startTime?: string
  endTime?: string
  entryOrderNumber?: string
  entryType?: string
  createdBy?: string
}

// 新增入库单参数接口
export interface AddInboundOrderParams {
  storageId: number
  entryOrderNumber: string
  entryType: string
  entryTime: string
  remarks: string
  createdTime: string
  createdBy: string
  modifiedBy: string
  modifiedTime: string
  isDelete: boolean
}

// 获取所有入库单
export const getAllInboundOrders = async (): Promise<ApiResponse<InboundOrder[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/InboundOrder/GetAll')
    return response.data
  } catch (error) {
    console.error('获取入库单失败:', error)
    throw error
  }
}

// 搜索入库单
export const searchInboundOrders = async (params: SearchParams): Promise<ApiResponse<InboundOrder[]>> => {
  try {
    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => value !== undefined && value !== '')
    )
    
    const response = await MES_LXK_ApiHost.get('/api/InboundOrder/GetAll', {
      params: filteredParams
    })
    return response.data
  } catch (error) {
    console.error('搜索入库单失败:', error)
    throw error
  }
}

// 获取产品列表
export const getProducts = async (): Promise<ApiResponse<Product[]>> => {
  try {
    // 尝试多个可能的API路径
    const possiblePaths = [
      '/api/ProductDetail/GetAll',
      '/api/Product/GetAll',
      '/api/ProductDetail/GetAllProductDetails',
      '/api/Product/GetAllProducts'
    ]
    
    let lastError = null
    
    for (const path of possiblePaths) {
      try {
        console.log('尝试API路径:', path)
        const response = await MES_LXK_ApiHost.get(path)
        console.log('API调用成功:', path, response.data)
        return response.data
      } catch (error: any) {
        console.log('API路径失败:', path, error.response?.status)
        lastError = error
        continue
      }
    }
    
    // 如果所有路径都失败，抛出最后一个错误
    throw lastError
  } catch (error) {
    console.error('获取产品列表失败:', error)
    throw error
  }
}

// 获取入库单明细（按入库单号）- 直接修复版本
export const getInboundOrderDetails = async (
  entryOrderNumber: string
): Promise<ApiResponse<any[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get(`/api/InboundOrder/GetProductDetails/${entryOrderNumber}`)
    
    // 直接返回标准格式，确保前端能正确处理
    return {
      code: 200,
      msg: 'OK',
      data: Array.isArray(response.data) ? response.data : []
    }
  } catch (error) {
    console.error('获取入库单明细失败:', error)
    throw error
  }
}

// 新增入库单
export const addInboundOrder = async (params: AddInboundOrderParams): Promise<ApiResponse<boolean>> => {
  try {
    // 添加调试日志
    console.log('新增入库单参数:', params)
    
    const response = await MES_LXK_ApiHost.post('/api/InboundOrder/Add', params)
    console.log('新增入库单响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('新增入库单失败:', error)
    // 添加更详细的错误信息
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    throw error
  }
}

// 更新入库单
export const updateInboundOrder = async (params: InboundOrder): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.put('/api/InboundOrder/Update', params)
    return response.data
  } catch (error) {
    console.error('更新入库单失败:', error)
    throw error
  }
}

// 删除入库单
export const deleteInboundOrder = async (id: number): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.delete(`/api/InboundOrder/Delete/${id}`)
    return response.data
  } catch (error) {
    console.error('删除入库单失败:', error)
    throw error
  }
}

// 导出入库单
export const exportInboundOrders = async (params: SearchParams): Promise<Blob> => {
  try {
    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => value !== undefined && value !== '')
    )
    
    const response = await MES_LXK_ApiHost.get('/api/InboundOrder/Export', {
      params: filteredParams,
      responseType: 'blob'
    })
    return response.data
  } catch (error) {
    console.error('导出入库单失败:', error)
    throw error
  }
}

// 新增入库单明细
export const addInboundOrderDetail = async (params: any): Promise<ApiResponse<boolean>> => {
  try {
    // 按优先级尝试多个后端端点，避免404
    const endpoints = [
      '/api/ProductDetail/Add',
      '/api/ProductDetail/AddProductDetail',
      '/api/InboundOrderDetail/Add'
    ]
    let lastErr: any
    for (const ep of endpoints) {
      try {
        console.log('尝试新增明细端点:', ep)
        const resp = await MES_LXK_ApiHost.post(ep, params)
        return resp.data
      } catch (e) {
        lastErr = e
        continue
      }
    }
    throw lastErr
  } catch (error) {
    console.error('新增入库单明细失败:', error)
    throw error
  }
}

// 更新入库单明细
export const updateInboundOrderDetail = async (params: any): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.put('/api/InboundOrderDetail/Update', params)
    return response.data
  } catch (error) {
    console.error('更新入库单明细失败:', error)
    throw error
  }
}

// 删除入库单明细
export const deleteInboundOrderDetail = async (id: number): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.delete(`/api/InboundOrderDetail/Delete/${id}`)
    return response.data
  } catch (error) {
    console.error('删除入库单明细失败:', error)
    throw error
  }
}

// 批量新增入库单明细
export const batchAddInboundOrderDetails = async (details: any[]): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.post('/api/InboundOrderDetail/Add', details)
    return response.data
  } catch (error) {
    console.error('批量新增入库单明细失败:', error)
    throw error
  }
}

// 保存入库单明细（使用正确的接口）
export const saveInboundOrderDetails = async (
  entryOrderNumber: string,
  details: any[],
  createdBy: string = 'admin',
  modifiedBy: string = 'admin'
): Promise<ApiResponse<{ okCount: number; failCount: number }>> => {
  try {
    console.log('开始保存入库单明细:', {
      entryOrderNumber,
      detailsCount: details.length,
      createdBy,
      modifiedBy
    })
    
    let okCount = 0
    let failCount = 0
    
    for (const detail of details) {
      // 确保entryOrderNumber字段正确传递，这是关键的关联字段
      const payload = {
        // 入库单号 - 多种格式确保兼容性
        entryOrderNumber: entryOrderNumber,
        EntryOrderNumber: entryOrderNumber,
        
        // 产品基本信息
        productId: detail.productId,
        productName: detail.productName,
        productNumber: detail.productNumber || detail.productCode,
        productCode: detail.productCode || detail.productNumber,
        productSpecification: detail.productSpecification || '',
        
        // 库存单位
        inventoryUnit: detail.inventoryUnit || detail.unit,
        unit: detail.unit || detail.inventoryUnit,
        
        // 产品属性
        productAttribute: detail.productAttribute || '',
        processRoute: detail.processRoute || '',
        
        // 库存数量
        maxInventory: detail.maxInventory || 0,
        minInventory: detail.minInventory || 0,
        safetyInventory: detail.safetyInventory || detail.safetyStock || 0,
        safetyStock: detail.safetyStock || detail.safetyInventory || 0,
        
        // 当前库存和入库数量
        current: detail.current || detail.currentInventory || 0,
        currentInventory: detail.currentInventory || detail.current || 0,
        inventoryQuantity: detail.inventoryQuantity || detail.num || 1,
        num: detail.num || detail.inventoryQuantity || 1,
        
        // 系统字段
        isDelete: detail.isDelete || false,
        createdBy: createdBy,
        modifiedBy: modifiedBy,
        createdTime: new Date().toISOString(),
        modifiedTime: new Date().toISOString()
      }
      
      console.log('准备保存明细:', {
        productName: detail.productName,
        entryOrderNumber: payload.entryOrderNumber,
        productId: payload.productId,
        num: payload.num
      })
      
      // 尝试多个可能的API端点
      const endpoints = [
        '/api/ProductDetail/AddProductDetail',
        '/api/ProductDetail/Add',
        '/api/InboundOrderDetail/Add'
      ]
      
      let saved = false
      for (const endpoint of endpoints) {
        try {
          console.log(`尝试端点: ${endpoint}`)
          const response = await MES_LXK_ApiHost.post(endpoint, payload)
          const resp = response.data
          console.log(`端点 ${endpoint} 响应:`, resp)
          
          if (resp && resp.code === 200) {
            console.log(`明细保存成功: ${detail.productName}`)
            okCount++
            saved = true
            break
          }
        } catch (error: any) {
          console.log(`端点 ${endpoint} 失败:`, error.response?.status, error.message)
          continue
        }
      }
      
      if (!saved) {
        console.error(`明细保存失败: ${detail.productName}`)
        failCount++
      }
    }
    
    console.log('明细保存完成:', { okCount, failCount })
    return { code: 200, msg: 'OK', data: { okCount, failCount } }
  } catch (error) {
    console.error('保存明细失败:', error)
    throw error
  }
}
